package com.ellecity06.common.utils

import android.app.Activity
import android.content.*
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.text.TextUtils
import android.util.Patterns
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.webkit.URLUtil
import java.net.MalformedURLException

/**
 * @author ellecity06
 * @time 2024/10/22 17:59
 * @des
 */
class CommonUtils {
    companion object{
        @JvmStatic
        fun isInstallAPIK(context: Context, packageName: String): Boolean {
            return if (packageName == null || "" == packageName) false else try {
                val info: ApplicationInfo = context.packageManager.getApplicationInfo(
                    packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES
                )
                true
            } catch (e: PackageManager.NameNotFoundException) {
                false
            }

        }
        /**
         * 检测是否安装支付宝
         * @return
         * @param context
         */
        @JvmStatic
        fun checkAliPayInstalled(context: Context): Boolean {
            val uri = Uri.parse("alipays://platformapi/startApp")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            val componentName: ComponentName? = intent.resolveActivity(context.packageManager)
            return componentName != null
        }
        /**
         * 检测是否安装微信
         * @return
         * @param context
         */
        @JvmStatic
        fun checkWeChatInstalled(context: Context): Boolean {
           return checkApkExist(context,"com.tencent.mm")
        }
        fun copyStr(activity: Activity, text: String?) {
            //获取剪贴版
            val clipboard: ClipboardManager =
                activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            //创建ClipData对象
            //第一个参数只是一个标记，随便传入。
            //第二个参数是要复制到剪贴版的内容
            val clip: ClipData = ClipData.newPlainText("simple text", text)
            //传入clipdata对象.
            clipboard.setPrimaryClip(clip)
        }

        /**
         * 检查是否安装应用
         */
        fun checkApkExist(context: Context, packageName: String?): Boolean {
            return if (packageName == null || "" == packageName) false else try {
                val info: ApplicationInfo = context.packageManager.getApplicationInfo(
                    packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES
                )
                true
            } catch (e: PackageManager.NameNotFoundException) {
                false
            }
        }

        fun isLink(url: String): Boolean {
            try {
                return URLUtil.isValidUrl(url) && Patterns.WEB_URL.matcher(url).matches()
            } catch (e: MalformedURLException) {
                return false
            }
//        return url.isNotEmpty() && (url.startsWith("http://") || url.startsWith("https://"))
        }

        /**
         * 获取App版本号
         */
        fun getVersion(context: Context): String? {
            var versionName = "1.0.0"
            try {
                val pm = context.packageManager
                val packageInfo: PackageInfo = pm.getPackageInfo(
                    context.packageName,
                    PackageManager.GET_ACTIVITIES
                )
                versionName = packageInfo.versionName
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }
            return versionName
        }
        /**
         * 获取App版本号
         */
        fun getVersionCode(context: Context): Int {
            var verCode = -1
            try {
                verCode =
                    context.packageManager.getPackageInfo(context.packageName, 0).versionCode
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }
            return verCode
        }
        /**
         * 获取App名称
         */
        fun getAppName(context: Context): String? {
            var appName: String? = null
            try {
                val packageManager = context.packageManager
                val info =
                    packageManager.getApplicationInfo(context.packageName, 0)
                appName = packageManager.getApplicationLabel(info) as String
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }
            return appName
        }

        /**
         * 弹出键盘
         */
        fun showKeyboard(v: View) {
            v.post {
                val imm: InputMethodManager = v.context
                    .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }

        /**
         * 隐藏键盘
         */
        fun hideKeyboard(v: View) {
            val imm: InputMethodManager = v.context
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (imm.isActive) {
                imm.hideSoftInputFromWindow(v.applicationWindowToken, 0)
            }
        }

        /**
         * 字符串中间部分转换为*  - 用于手机号或邮箱中间加*
         */
        fun addStarInMiddle(s: String): String? {
            if (TextUtils.isEmpty(s)) {
                return s
            }
            if (s.contains("@")) {
                val index = s.lastIndexOf("@")
                return if (index < 4) {
                    s
                } else s.substring(0, 3) + getStar(3) +
                        s.substring(index)
            }
            val len = s.length
            return if (len < 7) {
                s
            } else s.substring(0, 3) + getStar(len - 6) +
                    s.substring(len - 3)
        }

        /**
         * 字符串中间部分转换为*  - 前后各留3个字符
         */
        fun addStarLast3(s: String): String? {
            if (TextUtils.isEmpty(s) || s.length < 4) {
                return s
            }
            val len = s.length
            return if (len < 7) {
                s.substring(0, 3) + getStar(len - 3)
            } else s.substring(0, 3) + getStar(len - 6) +
                    s.substring(len - 3)
        }

        /**
         * 返回 length 长度的*号
         */
        fun getStar(length: Int): String {
            val star = StringBuffer()
            for (i in 0 until length) {
                star.append("*")
            }
            return star.toString()
        }

        /**
         * 数字每隔4位加空格
         */
        fun addSpaceInNum(cardNum: String): String? {
            if (TextUtils.isEmpty(cardNum)) {
                return cardNum
            }
            val number = StringBuffer()
            for (i in 0 until cardNum.length) {
                number.append(cardNum[i])
                if ((i + 1) % 4 == 0) {
                    number.append(" ")
                }
            }
            return number.toString()
        }
        fun buildTransaction(type: String?): String {
            return if (type == null) System.currentTimeMillis()
                .toString() else type + System.currentTimeMillis()
        }
    }
}